<template>
  <div>
    <a-menu
      v-model:selectedKeys="selectedKeys"
      mode="inline"
      :open-keys="openKeys"
      @openChange="onOpenChange"
      @click="handleClick"
      theme="light"
    >
      <a-sub-menu v-for="item in props.menuItems" :key="item.key">
        <template #icon>
          <MailOutlined />
        </template>
        <template #title>{{ item.name }}</template>
        <a-menu-item v-for="subItem in item.children" :key="subItem.key">
          <router-link :to="subItem.path">{{ subItem.name }}</router-link>
        </a-menu-item>
      </a-sub-menu>
    </a-menu>
  </div>
</template>
<script setup lang="ts">
  import { reactive, toRefs } from 'vue';
  import { MailOutlined } from '@ant-design/icons-vue';
  import type { MenuProps } from 'ant-design-vue';
  //todo 缺少icon声明
  interface MenuItem {
    key: string;
    name: string;
    icon?: any;
    path: string;
    children?: Array<MenuItem>;
  }
  const props = defineProps({
    menuItems: Array<MenuItem>,
  });
  const handleClick: MenuProps['onClick'] = (e) => {
    const key = e.key;
    console.log(key);
  };
  const state = reactive({
    rootSubmenuKeys: ['sub1', 'sub2', 'sub4'],
    openKeys: ['sub1'],
    selectedKeys: [],
  });
  const { selectedKeys, openKeys } = toRefs(state);
  const onOpenChange = (openKeys: string[]) => {
    const latestOpenKey = openKeys.find((key) => state.openKeys.indexOf(key) === -1);
    if (state.rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
      state.openKeys = openKeys;
    } else {
      state.openKeys = latestOpenKey ? [latestOpenKey] : [];
    }
  };
</script>
